/*
 * Serial IO manipulations header file
 *
 * Copyright (C) 2020 Long-Horn.
 *
 */
#ifndef SERIAL_IO_H
#define SERIAL_IO_H

#include <stdio.h>
#include <pthread.h>

#ifdef __cplusplus
extern "C"  {
#endif
#define SIO_OUT			0x01
#define SIO_IN			0x02

#define SIO_PARITY_NONE	0
#define SIO_PARITY_EVEN	1
#define SIO_PARITY_ODD	2

#define PORT_NAME_LEN 16

typedef struct
{  
    long baud;
    int parity;
    int stopbits;
    int databits;
    int xonxoff;
    char portname[PORT_NAME_LEN]; // for example: /dev/ttyS0
} serialinfo_s;

typedef struct _serial_io
{
    // interface functions
    int (* open)(void *sio);
    void (* close)(void *sio);
    int (* read)(void *sio, void *buffer, size_t count);
    int (* write)(void *sio, void *buffer, size_t count);
    int (* write_timeout)(void *sio, void *buffer, size_t count, size_t ms);
    int (* read_timeout)(void *sio, void *buffer, size_t count, size_t ms);
    int (* write_with_response)(void *sio, void *buffer, size_t count, void *response);
    void (* flush)(void *sio, int dir);
    void (* drain)(void *sio);

    // serial port informations
    int fd;
    serialinfo_s info;
    
    // synchronization primitives
    pthread_mutex_t write_mutex;
    pthread_mutex_t read_mutex;
} serial_io_s;

int create_serial_io(serial_io_s **sio, const char *portname, int baud_rate);
void destroy_serial_io(void *sio);

#ifdef __cplusplus
}
#endif

#endif	/* SERIAL_IO_H */
